varquestionsmanagermodule = angular.module("papermanager",[ 'angularFileUpload','ui.tree','dropdownApp', 'tm.pagination','vModal','btnconqitk','Common', 'knowledgebaseS', 'loadModule','knowledgeSelector','textUploadModule'])
.controller('questionsmanagercontroller', ['FileUploader', '$scope', '$rootScope', 'sysUserInfo','RequestTrainService','Comm', 'MsgCon', 'Msg','$sce','$stateParams','$state', function (FileUploader,$scope, $rootScope,sysUserInfo,RTS,  Comm, MsgCon, Msg,$sce,$stateParams, $state) {
    $scope.btnlist = { savefun: false, addinfo: false, editinfo: false, delinfo: false };
    $rootScope.btnTab = "index.Train.question";
   
   $scope.resTxt = "";
   $scope.paramsList = [];      
   $scope.openTxt = function(data,index){         
      $scope.paramsList[index] = $scope.paramsIsNull($scope.paramsList[index]);
      $scope.paramsList[index].txt  = data;      
      //隐藏其他上传按钮
      $scope.paramsList.forEach(function(data,index){
        if(data!=null&&data!=undefined&&data.hasOwnProperty("isShow")){
            data.isShow=false;
        }
      });
      $scope.paramsList[index].isShow = true;
   }    
   $scope.paramsIsNull = function(obj){
        if(!obj){
            obj = {};
        }
        if(!obj.hasOwnProperty("txt")){
        obj.txt = "";
        }
        if(!obj.hasOwnProperty("isShow")){
            obj.isShow = false;
        }
        return obj;
   }
   $scope.closeTxt = function(obj){
        //obj.isShow = false;
   } 
     //上传文件对象
    $scope.uploader = new FileUploader();

	/*******************************************************初始化*********************************************/
	$scope.params={
		pageIndex:"1",
		pageSize:"10",
		knowledge_Id:"",
		userid: sysUserInfo.getuserinfo().user_ID,
   		orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
    	powerLV: sysUserInfo.getuserinfo().powerLV,//登录人的系统角色
    	screenText:"",
    	screenType:"",
    	orderBy:"desc",
    	orderbyfield:"2",
    	paper_id:"",   
        type:"1"     
    };
    $scope.exportQue = function(){
        $scope.url=$rootScope.userurl+"/questionLook/findQuestionBySelectAndTrim?knowledge_Id="+$scope.params.knowledge_Id+"&userid="+$scope.params.userid+"&orgid="+$scope.params.orgid+"&powerLV="+$scope.params.powerLV+"&screenType="+$scope.screenobj.num+"&screenText="+(Comm.isNull($scope.searchText)?"":$scope.searchText)+"&orderBy="+$scope.params.orderBy+"&orderbyfield="+$scope.params.orderbyfield+"&paper_id="+$scope.params.paper_id+"&type=2";
        window.open($scope.url);
    }
    
    /*分页*/
    $scope.paginationConf = {
    	currentPage:1,
    	totalItems:0,
    	itemsPerPage: 10,
    	perPageOptions: [10, 20],
    	onChange: function () {
    		if( (parseInt($scope.params.pageIndex) !=parseInt($scope.paginationConf.currentPage))||(parseInt($scope.params.pageSize) !=parseInt($scope.paginationConf.itemsPerPage))){
    			if($scope.paginationConf.currentPage==0){$scope.paginationConf.currentPage=1;}
    			$scope.params.pageIndex =$scope.paginationConf.currentPage;
    			$scope.params.pageSize = $scope.paginationConf.itemsPerPage;
    			$scope.GetList();
    		}
    	}
    }

    /*******************************************************知识选择器*********************************************/
//配置知识选择器
     $scope.knowConfig = {   // 配置知识选择器的参数
     	menu: ["structure"],
        kssMore:false, //知识结构 是否多选
        kssList:[],    // 知识结构选中列表
        isShow:false,  // 显示知识选择器
      }; 

    //接收参数
    if($stateParams.examid!=""){
    	$scope.params.paper_id=$stateParams.examid;
    	
    	$scope.gobackexam=function(){
    		$state.go("index.Train.papermanager"); 
    	}
      $scope.subCreateHtmlLoading = false;
      $scope.subCreateHtml=function(){
            if($scope.subCreateHtmlLoading) // 防止多次点击
              return;
            $scope.subCreateHtmlLoading = true;                        
            RTS.IcreateHtml({userid: sysUserInfo.getuserinfo().user_ID,
   			orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
   			paper_id:$scope.params.paper_id}).then(function(data){
          $scope.subCreateHtmlLoading =false;   			
          if (data.errorcode == "0") {
            Msg.success("操作成功");
            $scope.gobackexam();

          }else{
            $scope.subCreateHtmlLoading =false;   			
            Msg.error("请求数据有误,无法进行编辑");
          }
        },function callback() {
          $scope.subCreateHtmlLoading =false;   			
          Msg.error("请求数据有误");
          $scope.isloading=false;   
        });
   		}
   	}
    /*************************************************知识选择器-题库选题***************************************************/
    //配置
    $scope.knowConfigQuestions = {   // 配置知识选择器的参数
      menu: ["question"],
        ksqMore:true, // 题目  是否多选
        ksqList:[],        // 题目选中列表
        isShow:false,   // 显示知识选择器
        callbackParams: {isClose:true}  // 默认通过窗口关闭
      }; 
    // 试题分数列表 筛选 1 单选 2 多选 3 判断 4 问答 5 填空 6 B型题 7 综合题   
    $scope.callbackQueInitList = [
    {
      name:"单选题",
      type:1,
            num:0,  //题目数量
            score:2 // 单题目分数
        },  // 单选题
        {
          name:"多选题",
          type:2,
          num:0,
          score:2
        },  // 多选题
        {
          name:"判断题",
          type:3,
          num:0,
          score:2
        },  // 判断题
        {
          name:"问答题",
          type:4,
          num:0,
          score:2
        },  // 问答题
        {
          name:"填空题",
          type:5,
          num:0,
          score:2
        },  // 填空题
        {
          name:"B型题",
          type:6,
          num:0,
          cnum:0,
          score:2
        },  // B型题
        {
          name:"综合题",
          type:7,
          num:0,
          cnum:0,
          score:2
        }   // 综合题
        ];
    //拷贝到前台数组
    $scope.questionsScoreList = angular.copy($scope.callbackQueInitList);
    // 打开题库选择器
    $scope.questionsOpen =function(){        
      $scope.knowConfigQuestions.isShow = true;
    }
    // 回调选择的试题
    $scope.onCallbackCheckQuestions = function(){            
        if($scope.knowConfigQuestions.callbackParams.isClose){ // 这个时候是关闭按扭点击的
          $scope.knowConfigQuestions.isShow = false;
          return;
        }       
        if($scope.knowConfigQuestions.ksqList.length <=0){
          Msg.info("提示","请选择您要添加的题目!");
          return;
        }
        //为了提高筛选性能进行删减
        $scope.callbackQuestionsList = angular.copy($scope.knowConfigQuestions.ksqList);
        //每次都 需要初始化
        $scope.questionsScoreList = angular.copy($scope.callbackQueInitList);
        // 处理试题分数 以及显示情况       
        angular.forEach($scope.questionsScoreList,function(qdata,qindex,qarray){    // 试题类型遍历
            angular.forEach($scope.callbackQuestionsList,function(data,index,array){ // 遍历选中的试题                                
                if(qdata.type == data.questions_Type){ // 如果类型相同                                    
                  qdata.num = qdata.num + 1;                   
                    if(data.questions_Type  == "6" || data.questions_Type == "7" ){ // B型题 和综合题需要单独处理
                        // 拆包
                        $scope.bTypenObj = JSON.parse(data.questions_Json);                                               
                        qdata.cnum+= JSON.parse($scope.bTypenObj.answerAnalysis).length;                                             
                      }
                    }
                  });            
          });
        // 正式录入试题
        $scope.setQuestionsScoreShow = true;            
      }
      /*******************************设置分数*************************/
      $scope.setQuestionsScoreShow = false;

    // 取消分数设置
    $scope.closeQuestionsScore = function(){
      $scope.setQuestionsScoreShow = false;    
    }
    // 按钮loading
    $scope.isBtnLoading = false;
    // 保存试题
    $scope.saveQuestionsScore = function(){
      $scope.paramsQuestionsList = [];
        // 处理集合数据
        angular.forEach($scope.questionsScoreList,function(qdata,qindex,qarray){    // 试题类型遍历
            angular.forEach($scope.knowConfigQuestions.ksqList,function(data,index,array){ // 遍历选中的试题                                
                if(qdata.type == data.questions_Type){ // 如果类型相同    
                    if(data.score == undefined || data.score == null || data.score == ""){
                        data.score = 0;
                    }
                    if(data.questions_Type == "6" || data.questions_Type == "7"){ // B 型题 | 综合题 需要对分数单独处理
                        // 拆包
                        $scope.bTypenObj = JSON.parse(data.questions_Json);                                               
                        $scope.bTypeChile = JSON.parse($scope.bTypenObj.answerAnalysis);                       
                        angular.forEach($scope.bTypeChile,function(chile,cindex,carray){
                          chile.score = qdata.score;                
                          data.score += chile.score;                            
                        });
                      //转字符串
                       $scope.bTypenObj.answerAnalysis = JSON.stringify($scope.bTypeChile); //回转为字符串
                       data.questions_Json = JSON.stringify($scope.bTypenObj); // 试题对象回转为字符串
                       $scope.paramsQuestionsList.push(data);
                     }else{
                      data.score = qdata.score                    
                      $scope.paramsQuestionsList.push({questions_Id:data.questions_Id,score: qdata.score, questions_Type: data.questions_Type}); 
                    }                                        
                  }
                });            
          });
        $scope.isBtnQuestionsLoading =true;

        //发送请求        
        RTS.questionsToPaper({ksqList:$scope.paramsQuestionsList, paper_id:$scope.params.paper_id}).then(function(response){
          if(response.errorcode == "0"){
                $scope.isBtnQuestionsLoading =false; // 关闭loading       
                $scope.setQuestionsScoreShow = false;   // 关闭 设置分数
                $scope.knowConfigQuestions.isShow = false; // 关闭 选择器
                $scope.knowConfigQuestions.ksqList = []; //初始化选中题目
                $scope.GetList();
                Msg.success("题目导入成功！");
              }else{
                Msg.error("题目导入失败！");
                $scope.isBtnQuestionsLoading =false; // 关闭loading       
              }
            }, function callback() {
              Msg.error("题目导入失败");
            $scope.isBtnQuestionsLoading =false; // 关闭loading       
          });        
      }

      /**************************************排序显示***********************************************************/
        $scope.ShowOk=false;//排序显示控制
        $scope.orderby="desc";
        //排序数组
        $scope.OrderName="上传时间";
        $scope.params.orderBy=$scope.orderby;
        $scope.params.orderbyfield=2;
        $scope.orderlist=[{name:"题目名称",num:1},
        {name:"上传时间",num:2}
        ];

        //$scope.params.orderbyfield=1;
        //课件排序
        $scope.OrderByFun=function(Typenum,Ordername){
        	if($scope.OrderName==Ordername){
        		if($scope.orderby=="asc"){
        			$scope.orderby="desc";
        		}else{
        			$scope.orderby="asc";
        		}
        	}else{
        		$scope.orderby="desc";
        	}
        	$scope.ShowOk=false;
        	$scope.OrderName=Ordername;
        	$scope.params.orderBy=$scope.orderby;
        	$scope.params.orderbyfield=Typenum;
        	$scope.GetList();
        }

        /*********************************************************************************筛序初始化*********************************************/
        $scope.buttonshow=true;
        $scope.cite=false;
        $scope.clickFunSHow=function(){
        	$scope.cite=!$scope.cite;
        }

        $scope.questionType="";
        $scope.screenlist=[
        {name:"题目名称",num:"1"},
        {name:"出题人",num:"4"},
        {name:"题型",num:"3"},
        {name:"选择知识分类",num:"2"}
        ];
        //切换题型
        $scope.typeChange=function(){
            $scope.searchText=$scope.questionType;
        }

        $scope.screenobj={name:"题目名称",num:1};
        $scope.screenname="题目名称";
        $scope.screenFun=function(obj){
          $scope.paginationConf.currentPage=1;
        	if (obj!=undefined&&obj!=null) {
        		$scope.screenobj=obj;
        	}
        	
        	$scope.buttonshow=true;
        	$scope.searchText="";
        	switch ($scope.screenobj.num) {
        		case"1":
        		$scope.screenname="题目名称";
        		break;
        		case"4":
        		$scope.screenname="出题人";
        		break;
        		case"2":
        		$scope.knowConfig.isShow=true;
        		$scope.buttonshow=false;
        		break;
        	}
        	$scope.params.screenType=$scope.screenobj.num;
        }


 //查询按钮
 $scope.ButtonGet=function(){
 	$scope.params.screenType=$scope.screenobj.num;
 	$scope.params.screenText=$scope.searchText;
 	$scope.GetList();
 }

//知识结构选中
$scope.onCallbackSer = function(obj){
	$scope.knowConfig.isShow=false;
	if($scope.knowConfig.kssList != null && $scope.knowConfig.kssList.length >0){
		$scope.params.knowledge_Id= $scope.knowConfig.kssList[0].knowledge_Id;
		$scope.searchText=$scope.knowConfig.kssList[0].knowledge_Name;
		$scope.knowConfig.knowledge_Id=$scope.knowConfig.kssList[0].knowledge_Id;
		$scope.GetList();
	}else{
		$scope.params.knowledge_Id="";
	}

}
/*******************************************************查询题目列表*********************************************/
$scope.headurl=$rootScope.requestUrl;

 //查询试卷列表
 $scope.GetList=function(){
 	if($scope.isloading){
 		Msg.info("正在查询，请稍后!");
 		return;
 	}
 	$scope.isloading=true;
 	RTS.findQuestionBySelectAndTrim($scope.params).then(function(data){
 		$scope.isloading=false;      
        //2下载
        if($scope.params.type==2||$scope.params.type=="2"){
            $scope.params.type=1;
        //查询
        }else{
 		    if (data.errorcode == "0") {
 			    $scope.List=data.datas;
 			    if ($scope.List==undefined|| $scope.List.length<=0) {
 				
 				    return;
 			    }else {
 				
 				    $scope.List.forEach( function(element, index) {
 					    element.questions_Json=$scope.questionJsonFun(element.questions_Json);
 				    });
 				    $scope.paginationConf.totalItems = data.numCount;
 				    $scope.paginationConf.currentPage = data.pageIndex;  
 			    }
 		    }else{

 			    Msg.error("请求数据有误");
 		    }
        }
 	}, function callback() {
 		Msg.error("请求数据有误");
 		$scope.isloading=false;   
 	});
 }
 //将试题对象解析
 $scope.questionJsonFun=function(obj){
// 	console.log(obj);
// 	console.log(JSON.parse(obj));
return JSON.parse(obj);


}
//题型集合
$scope.questions_Typelist=[
{name:"单选题",num:"1"},
{name:"多选题",num:"2"},
{name:"判断题",num:"3"},
{name:"问答题",num:"4"},
{name:"填空题",num:"5"},
{name:"B型题",num:"6"},
{name:"综合题",num:"7"}];


$scope.bindquestions_Typelist=function(num){
	var objname="";
	
	$scope.questions_Typelist.forEach(function(domobj){
		if (domobj.num==num) {
			objname=domobj.name;
			return;
		}
	});
	return objname;
}
$scope.bindquestions_answer=function(obj){
	var objname="";
	
	if (obj.questions_Type=="5") {
		obj.questions_Json.answer.split("///").forEach( function(element, index) {
			if (index==0) {
				objname=element;
			}else {
				objname+="|"+element;
			}
		}); ;
	}else {
		objname=obj.questions_Json.answer;
	}

	return objname;
}


/****************************************************新增编辑页面********************************************************************************/
   	//列表编辑图标
     $scope.addinfo=function(obj){
         if(!$scope.btnlist.editinfo){
            Msg.warning("无权限操作！");
            return;
        }
          $scope.selectList=[obj];
          $scope.isHideFun(1);
    }

   	$scope.windowsClose=false; //窗口关闭
   	$scope.isHideFun=function(val){//新增编辑页显示隐藏
   		$scope.clearQuesText();
   		if (val==0) {//新增
   			$scope.initquestionobj();
   			$scope.OptionInitFun();
   		}else if(val==1) {
   			if ($scope.selectList.length<=0) {
   				return Msg.warning("请选择要编辑的题目!");
   			}else if($scope.selectList.length>1){
   				return Msg.warning("只能选择一道题目进行编辑!");
   			}else{
   				$scope.GetquestionObj();
   			}

   		}else if(val ==2){
   			$scope.OpenQueHtml($scope.params.paper_id);
   			$scope.windowsClose=true;
   		}
   		$scope.windowsClose=!$scope.windowsClose;
   	}



   //编辑 获取题目对象
   $scope.GetquestionObj=function(){
   	$scope.isloading=true;

   	RTS.questionFindByid({questions_Id:$scope.selectList[0].questions_Id,userid: sysUserInfo.getuserinfo().user_ID,
   			orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
   			powerLV: sysUserInfo.getuserinfo().powerLV,paper_id:$scope.params.paper_id}).then(function(data){
   				$scope.isloading=false;
   				if (data.errorcode == "0") {
   					
   					
   					
   					$scope.questionObj=data.datas.examobj;
   					$scope.questionObj.userid= sysUserInfo.getuserinfo().user_ID;
   					$scope.questionObj.orgid= sysUserInfo.getuserinfo().organization_ID;// 企业id
    				$scope.questionObj.powerLV= sysUserInfo.getuserinfo().powerLV;//登录人的系统角色
    				$scope.questionObj.userName=sysUserInfo.getuserinfo().user_Name;
    				$scope.questionObj.upd_Date='';
    				$scope.questionObj.create_Date='';
    				$scope.JsonanalysisFun();
    				$scope.OptionInitFun("init");
    			}else{
    				Msg.error("请求数据有误,无法进行编辑");
    			}
    		},function callback() {
    			Msg.error("请求数据有误");
    			$scope.isloading=false;   
    		});
   		}
   		$scope.paperDifficultylist=[
   		{"name":"简单","num":"1"},
   		{"name":"一般","num":"2"},
   		{"name":"困难","num":"3"}
   		
   		];

//配置知识选择器
     $scope.knowConfigAdd = {   // 配置知识选择器的参数
     	menu: ["structure"],
        kssMore:false, //知识结构 是否多选
        kssList:[],    // 知识结构选中列表
        isShow:false,  // 显示知识选择器
      }; 

    //知识结构选中
    $scope.onCallbackSerAdd = function(obj){
    	$scope.knowConfigAdd.isShow=false;
    	if($scope.knowConfigAdd.kssList != null && $scope.knowConfigAdd.kssList.length >0){
    		$scope.questionObj.knowledge_Id= $scope.knowConfigAdd.kssList[0].knowledge_Id;
    		$scope.questionObj.knowledge_Name=$scope.knowConfigAdd.kssList[0].knowledge_Name;
    		$scope.knowConfigAdd.knowledge_Id=$scope.knowConfigAdd.kssList[0].knowledge_Id;
    	}

    }
   	 //声明题目对象
   	 $scope.initquestionobj=function(){

   	 	$scope.questionObj={
   	 		userid: sysUserInfo.getuserinfo().user_ID,
   			org_ID: sysUserInfo.getuserinfo().organization_ID,   // 企业id
    		powerLV: sysUserInfo.getuserinfo().powerLV,//登录人的系统角色
    		userName:sysUserInfo.getuserinfo().user_Name,
    		org_Name:sysUserInfo.getuserinfo().organization_Name,
    		questions_Id:"",
    		question_name:"",
			knowledge_Name:"",//知识结构分类名称
			knowledge_Id:"",
			questions_Type:"1",
			difficulty:"1",
			label:"",
			create_Id: sysUserInfo.getuserinfo().user_ID,
			create_Name:sysUserInfo.getuserinfo().user_Name,
			questions_Json:"",
			paper_id:$scope.params.paper_id,
			title:""

		};	
		$scope.OptionList=[];
		
	}

	//声明B型题子题对象
	$scope.NewBxingQuestionObj=function(){
		return {
			title:"",
			option:"",
			answerAnalysis:"",
			score:0
		};
	}
	//B型题集合
	$scope.BxingQuestionList=[];
	
	//B型题子题添加
	$scope.AddBxingQuestionListFun=function(){
		$scope.BxingQuestionList.push($scope.NewBxingQuestionObj());
	}
	//B型题子题删除
	$scope.DelBxingQuestionListFun=function(val){
		$scope.BxingQuestionList.splice(val,1);

	}

	//综合题子题集合
	$scope.comprehensiveChildList=[];

	//综合题子题集合删除
	$scope.clearcomprehensiveChildList=function(val,comprehensiveChildList){
		$scope.comprehensiveChildList.splice($scope.containscomprehensive(comprehensiveChildList,val),1);
	}

	$scope.containscomprehensive = function (arr, obj) {
		try {
			var i = arr.length;
			while (i--) {
				if (arr[i].id === obj.id) {
					return i;
				}
			}
			return -1;
		} catch (e) {
			return -1;
		}
	}
	var guid = new GUID();
	//综合题对象
	$scope.NewcomprehensiveChildObj=function(type){
		return{
			OptionList:angular.copy($scope.OptionList),
			type:type,
			answer:"",
			id:guid.newGUID(),
			title:"",
			answerAnalysis:"",
			score:0
		}
	}

	//添加综合题子题
	$scope.comprehensiveChildOption=function(val){
		var obj=$scope.NewcomprehensiveChildObj(val);
		$scope.comprehensiveChildList.push(obj);
		for(var j = 0, length2 = 4-obj.OptionList.length; j < length2; j++){
			$scope.addOptionlist(obj);
		}
		
	}




	//填空题的答案集合
	$scope.questiontiankonganswerList=[];
	$scope.questiontiankonganswerListHtml=function(val){

    val=val.replace("(","").replace(")","").replace("（","").replace("）","");
    if (val.trim()=="") {
      return "请在对应的括号内填写答案";
    }else {
      return val.trim();
    }
	}
	$scope.questiontiankonganswerFun=function(){
			//var str = "afsfd(bcd)asfasfsad(def)as（英文）dfsadf";
			pattern =new RegExp("[\\（|\\(](.|)*?[\\）|\\)]", "igm"); //得到填空题的内容   
			//取出匹配正则表达式的内容
			$scope.questiontiankonganswerList=$scope.questionObj.question_name.match(pattern);
		}
  $scope.$watch('questiontiankonganswerList', function (newValue, oldValue, scope) {
    var examresult="";
      try{
        examresult=JSON.parse(document.getElementById('itemobj').value).message;
      }
      catch(e){
       //console.log(e);
     }
     if (examresult!="") {
        $scope.params.knowledge_Id="";
        $scope.GetList();
      }

     
  }, true);


   $scope.AddOptionFun=function(){
     if ($scope.questionObj.questions_Id!=""&&$scope.OptionList.length>0) {
      return;
    }
			//$scope.isShow=true;
			if ($scope.questionObj.questions_Type=="6") {
				if ($scope.questionObj.questions_Id!=""&&$scope.BxingQuestionList.length>0) {
					return;
				}
				for(var j = 0, length2 = 4-$scope.BxingQuestionList.length; j < length2; j++){
					$scope.addOptionlist();
				}
				return;
			}
			if ($scope.OptionList.length<=0) {
				for(var j = 0, length2 = 4; j < length2; j++){
					$scope.addOptionlist();
				}
			}
		};
		
		//根据不同类型 初始化
		
		$scope.OptionInitFun=function(val){

            //初始化指令的参数
            var obj=$scope.paramsList[0];
            $scope.paramsList = [];   
            $scope.paramsList.push(obj);

			if (val==""||val==undefined) {
				$scope.clearQuesText();	
			}
			$scope.isShow=true;
			$scope.addOptiontext="增加选项";
			$scope.ClearOption=function(){
				$scope.OptionList=[];
				$scope.isShow=false;
			}
			switch ($scope.questionObj.questions_Type) {
					case "1"://单选题
					$scope.placeholdertitle="例如：1+1=?";
					$scope.AddOptionFun();
					break;
					case"2"://多选题

					$scope.placeholdertitle="例如：1+1=?";
					$scope.AddOptionFun();
					break;;
					case"3"://判断题
					$scope.placeholdertitle="例如：1+1=2 是否正确?";
					//$scope.ClearOption();
					break;;
					case"4"://问答题
					$scope.placeholdertitle="例如：请根据此题目填写你的回答";
					//$scope.ClearOption();
					break;
					case"5"://填空题
					$scope.placeholdertitle="例如：1+(需要填写的答案)=2 或 1+(需要填写的答案)+(需要填写的答案)=3";
					//$scope.ClearOption();
					break;
					case"6"://B型题
					$scope.placeholdertitle="例如：A、1 B、2 C、3";
					$scope.addOptiontext="增加子题";
					$scope.AddOptionFun();
					break;
					case"7"://综合题
					$scope.placeholdertitle="例如：请阅读本文。作答以下问题";
					$scope.questions_Json.score=0;
					$scope.comprehensiveChildList.forEach(function(element,index){
						$scope.questions_Json.score+= parseInt(element.score);
					});
					//$scope.ClearOption();
					break;
				}
				//return isShow;
			}

	//根据不同题型 展示不同选项
	$scope.questionOptionListShow=function(val){
		try {
			$scope.isreadonly=false;
			if ($scope.questionObj.questions_Type=="6") {
				$scope.questions_Json.score=0;
				$scope.BxingQuestionList.forEach(function(element,index){
					$scope.questions_Json.score+=parseInt(element.score);
				});
				$scope.isreadonly=true;
			}else if ($scope.questionObj.questions_Type=="7") {
				$scope.questions_Json.score=0;
				$scope.comprehensiveChildList.forEach(function(element,index){
					$scope.questions_Json.score+=parseInt(element.score);
				});
				$scope.isreadonly=true;
			}
			if ($scope.questionObj.questions_Type==val) {
				if ($scope.questionObj.questions_Type=="5") {
					$scope.questiontiankonganswerFun();
				}
				return true;
			}else {
				return false;
			}
		} catch(e) {
			// statements

		}
		

	}
	$scope.questions_Json={
		answer:"",
		answerAnalysis:"",
		options:[],
		title:"",
		score:0
	};
		//选项规则
		$scope.optionChar=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","X","Y","Z"];
		$scope.OptionList=[];
		$scope.newOption=function(index,comprehensiveChilditem){
		if (comprehensiveChilditem==undefined||comprehensiveChilditem=="") {//非综合题
			if (index==-1)
			{
				return{
					option:$scope.optionChar[$scope.OptionList.length],
					optionvalue:"",
					sort:$scope.OptionList.length,
					check:false
				};
			}else{
				return{
					option:$scope.optionChar[index],
					optionvalue:"",
					sort:index,
					check:false
				};
			}
		}else {
			if (index==-1)
			{
				return{
					option:$scope.optionChar[comprehensiveChilditem.OptionList.length],
					optionvalue:"",
					sort:comprehensiveChilditem.OptionList.length,
					check:false
				};
			}else{
				return{
					option:$scope.optionChar[index],
					optionvalue:"",
					sort:index,
					check:false
				};
			}
		}


	}
//增加时，判断是否有中间删除的。如果有 新增时 补回
$scope.OptionHasFun=function(comprehensiveChilditem){
	var obj="";
			if (comprehensiveChilditem==""||comprehensiveChilditem==undefined) {//非综合题
				$scope.OptionList.forEach( function(element, index) {
					if (element.option!=$scope.optionChar[index]) {
						
						if (obj=="") {
							obj=$scope.newOption(index);
						}
					}
				}); 
				if (obj=="") {
					obj=$scope.newOption(-1);
				}
			}else {

				comprehensiveChilditem.OptionList.forEach( function(element, index) {
					if (element.option!=$scope.optionChar[index]) {
						
						if (obj=="") {
							obj=$scope.newOption(index,comprehensiveChilditem);
						}
					}
				}); 
				if (obj=="") {
					obj=$scope.newOption(-1,comprehensiveChilditem);
				}
			}
			
			return obj;
		}

		
		
	//添加选项
	$scope.addOptionlist=function(comprehensiveChilditem){
		
		if ($scope.questionObj.questions_Type=="6") {
			$scope.AddBxingQuestionListFun();
			return;
		}
		
		if (comprehensiveChilditem==""|comprehensiveChilditem==undefined) {//非综合题
			var queobj=$scope.OptionHasFun();
			$scope.OptionList.push(queobj);
			$scope.OptionList=$scope.OptionList.sort(function(obj1,obj2){
				return obj1.sort-obj2.sort;
			});
		}else {//综合题
			var queobj=$scope.OptionHasFun(comprehensiveChilditem);
			comprehensiveChilditem.OptionList.push(queobj);
			comprehensiveChilditem.OptionList=comprehensiveChilditem.OptionList.sort(function(obj1,obj2){
				return obj1.sort-obj2.sort;
			});

		}
		
	}
	//删除选项
	$scope.delOptionlist=function(obj,comprehensiveChilditem){
		
		if (comprehensiveChilditem==""||comprehensiveChilditem==undefined) {
			$scope.OptionList.splice($scope.containsQue($scope.OptionList,obj),1);	
		}
		else {
			comprehensiveChilditem.OptionList.splice($scope.containsQue(comprehensiveChilditem.OptionList,obj),1);	
		}
		
	}
	
	$scope.containsQue = function (arr, obj) {
		try {
			var i = arr.length;
			while (i--) {

				if (arr[i].option === obj.option) {
					return i;
				}
			}
			return -1;
		} catch (e) {
			return -1;
		}
	}



	//根据不同的题型 选取答案答案
	$scope.questionAnswerFun=function(val,comprehensiveChilditem){
		if (comprehensiveChilditem==""||comprehensiveChilditem==undefined) {//非综合题
			switch ($scope.questionObj.questions_Type) {
					 	case "1"://单选题
					 	$scope.OptionList.forEach( function(element, index) {
					 		if (index==val) {
					 			element.check=true;
					 		}else {
					 			element.check=false;
					 		}
					 	});
					 	break;
					 	case"2"://多选题
					 	$scope.OptionList[val].check=!$scope.OptionList[val].check;
					 	break;
					 	case "4"://问答题
					 	$scope.questions_Json.answer="";
					 	break;
						case "3"://判断题
						$scope.questions_Json.answer=val;
						break;
					} 
				}else {
			switch (comprehensiveChilditem.type) {//综合题
					 	case "1"://单选题
					 	comprehensiveChilditem.OptionList.forEach( function(element, index) {
					 		if (index==val) {
					 			element.check=true;
					 		}else {
					 			element.check=false;
					 		}
					 	});
					 	break;
					 	case"2"://多选题
					 	comprehensiveChilditem.OptionList[val].check=!comprehensiveChilditem.OptionList[val].check;
					 	break;
					 	case "4"://问答题
					 	comprehensiveChilditem.answer="";
					 	break;
						case "3"://判断题
						comprehensiveChilditem.answer=val;
						break;
					}		
				}
			}
	//根据不同类型题目 不同的获取答案
	$scope.btnAnswerGet=function(){
		var ischeck=true;

		function ischeckFun(val,type){
			if (!val) {
				ischeck=false;
				if (type==1) {//答案
					Msg.info("答案不能为空,请填写或在选项左边设置答案!");

				}else {//选项
					Msg.info("选项不能为空,请填写或则删除该选项!");
				}
			}

			
		}
		
		$scope.questions_Json.options=[];//选项
				
		switch ($scope.questionObj.questions_Type) {
			case "1"://单选题
			$scope.questions_Json.answer="";
			$scope.OptionList.forEach( function(element, index) {
				$scope.questions_Json.options.push(element.optionvalue);
				if (element.check) {
					$scope.questions_Json.answer=element.option;
				}
				ischeckFun(element.optionvalue,2);

				
			});

			ischeckFun($scope.questions_Json.answer,1)
			break;
			case "2":
			$scope.questions_Json.answer="";
			$scope.OptionList.forEach( function(element, index) {
				$scope.questions_Json.options.push(element.optionvalue);
				if (element.check) {
					$scope.questions_Json.answer+=element.option;
				}
				ischeckFun(element.optionvalue,2);
			});
			ischeckFun($scope.questions_Json.answer,1);
			break;
			case"5"://填空题
			$scope.questions_Json.answer="";
			if($scope.questiontiankonganswerList==undefined||$scope.questiontiankonganswerList==null){
				Msg.warning("未检测到该题答案，请检查题目！");
				return;
			}
			$scope.questiontiankonganswerList.forEach( function(element, index) {
				$scope.questionObj.question_name=$scope.questionObj.question_name.replace(element,"()");
				if (index==0) {
					$scope.questions_Json.answer=$scope.questiontiankonganswerListHtml(element);
				}else {
					$scope.questions_Json.answer+="///"+$scope.questiontiankonganswerListHtml(element);
				}
			});
			ischeckFun($scope.questions_Json.answer,1);

			break;
			case"6"://B型题
      var Bsivestr=[];
      $scope.questions_Json.answer="";
      $scope.questions_Json.title+="  \n";
      $scope.BxingQuestionList.forEach( function(element, index) {
        Bsivestr.push(
        {
         create_Date:"",
         difficulty:$scope.questions_Json.difficulty,
         knowledge_Name:$scope.questions_Json.knowledge_Name,
         questions_Json:JSON.stringify({
          answer:element.option,
          answerAnalysis:element.answerAnalysis,
          title:element.title
        }),
         questions_Type:"6",
         score:element.score
       });

        ischeckFun(element.title,2);
        ischeckFun(element.option,1);
        $scope.questions_Json.answer+=element.option;
        $scope.questions_Json.title+="  小题分支： "+element.title;
      });
      $scope.questions_Json.answerAnalysis=JSON.stringify(Bsivestr);
      break;
      case"7":
			// $scope.questions_Json.answerAnalysis=
			$scope.comprehensivestr=[];
			$scope.comprehensiveChildList.forEach(function(element, index) {
				var obj=angular.copy($scope.questions_Json);
				obj.answerAnalysis=element.answerAnalysis;
				obj.score=element.score;
				switch (element.type) {
					case "1"://单选题
					element.OptionList.forEach( function(child, index) {
						obj.options.push(child.optionvalue);
						if (child.check) {
							obj.answer=child.option;
						}

						ischeckFun(child.optionvalue,2);

					});
					obj.title="[单选]"+element.title;
					
					ischeckFun(obj.answer,1);
					
					break;
				case "2"://多选题
				element.OptionList.forEach( function(child, index) {
					obj.options.push(child.optionvalue);
					if (child.check) {
						obj.answer+=child.option;
					}
					ischeckFun(child.optionvalue,2);
					
				});
				obj.title="[多选]"+element.title;
				
				ischeckFun(obj.answer,1);
				
				break;

					case "3"://判断题
					obj.title="[判断]"+element.title;
					obj.answer=element.answer;
					ischeckFun(obj.answer,1);
					break;

					case "4"://问答题
					obj.title="[问答]"+element.title;
					break;

				}

				
				$scope.comprehensivestr.push({questions_Json:obj,questions_Type:element.type,score:element.score});
			});
			$scope.questions_Json.answerAnalysis=JSON.stringify($scope.comprehensivestr);
			
			break;
		}
        $scope.questions_Json.title=$scope.questionObj.question_name;
		return ischeck;
	}
    //保存
    $scope.btnSave=function(){
    	if(!$scope.btnAnswerGet()){
    		return;
    	};
        if($scope.questionObj.knowledge_Id==null||$scope.questionObj.knowledge_Id.length<=0){
            Msg.warning("请选择知识结构");
            return;
        } 
        if(sysUserInfo.getuserinfo().powerLV==1){
            $scope.questionObj.position_type=1;//超管新增，公共题库
        }else{
            $scope.questionObj.position_type=0;//私有题库
        }
        
    	//console.log($scope.questions_Json);
    	$scope.questionObj.questions_Json=JSON.stringify($scope.questions_Json);
    	$scope.isloading=true;
        $scope.questionObj.paper_id=$scope.params.paper_id;
//    	console.log($scope.questionObj);
        $scope.questionObj2=$scope.questionObj;

        $scope.questionObj2.questions_Json=base64encode(encodeURI($scope.questionObj2.questions_Json));
        $scope.questionObj2.question_name=base64encode(encodeURI($scope.questionObj2.question_name));

        RTS.questionSaveOrUpdate($scope.questionObj2).then(function(data){
          $scope.isloading=false;
          $scope.windowsClose=false;
          if (data.errorcode == "0") {
                //    			console.log(data.datas);
                $scope.TipShow();
                data.datas.examobj.questions_Json=$scope.questionJsonFun(data.datas.examobj.questions_Json);
                $scope.GetList();
                $scope.OptionList=[];
                $scope.initquestionobj();

            }else{
             Msg.error("请求数据有误");
            }
        },function callback() {
          Msg.error("请求数据有误");
          $scope.isloading=false;   
        });
}

	//根据不同的题型 解析不同的json数据呈现
	$scope.JsonanalysisFun=function(){
		
		$scope.questions_Json=JSON.parse($scope.questionObj.questions_Json);

		$scope.questions_Json.score=$scope.questionObj.score;

			//$scope.OptionList=$scope.questions_Json.options;

			function answertrim(val){ //去除判断题特殊字符
				if (val+"".indexOf("对")) {
					return "对";
				}else {
					return "错";
				}
			}
			switch ($scope.questionObj.questions_Type) {
			case "1"://单选题
			$scope.questions_Json.options.forEach( function(element, index) {
				$scope.OptionList.push({option:$scope.optionChar[index],
					optionvalue:element,
					sort:index,
					check:false});
				if ($scope.questions_Json.answer==$scope.optionChar[index]) {
					$scope.OptionList[index].check=true;
				}

			});
			break;
				case"2"://多选题
				$scope.questions_Json.options.forEach( function(element, index) {
					$scope.OptionList.push({option:$scope.optionChar[index],
						optionvalue:element,
						sort:index,
						check:false});
					if ($scope.questions_Json.answer.indexOf($scope.optionChar[index])!=-1) {
						$scope.OptionList[index].check=true;
					}

				});

				break;
				case "3"://判断题
//				console.log($scope.questions_Json.answer);
$scope.questionObj.answer=answertrim($scope.questions_Json.answer);
break;
				case"5"://填空题
				$scope.questionObj.question_name=$scope.questions_Json.title;
       var question_name="";
       $scope.questionObj.question_name=$scope.questionObj.question_name.replace(/\（/g,'(').replace(/\）/g,')');

				//console.log($scope.questionObj.question_name.replace("（","(").replace("）",")"));
				var answerindex=0;
				$scope.questionObj.question_name.split("()").forEach( function(element, index) {										
                    if($scope.questions_Json.answer.split('///').length-1 >= answerindex){
					    element+="("+$scope.questions_Json.answer.split('///')[answerindex]+")";
					    answerindex++;					
                    }
					question_name+=element;
				});
				// $scope.questions_Json.answer.split('///').forEach( function(element, index) {
				// if ($scope.questionObj.question_name) {}

				// 		console.log(question_name);

				// });
				$scope.questionObj.question_name=question_name;
				
				
				
				// $scope.questiontiankonganswerList.forEach( function(element, index) {

				// });
				break;
				case "6"://B型题

				JSON.parse($scope.questions_Json.answerAnalysis).forEach( function(element, index) {
					element.questions_Json=JSON.parse(element.questions_Json);
					$scope.BxingQuestionList.push({
						title:element.questions_Json.title,
						option:element.questions_Json.answer,
						answerAnalysis:element.questions_Json.answerAnalysis,
						score:element.score
					});
				});
				

				break;
				case"7"://综合题
				
				//解析 并循环综合题子题数组 然后将对象插入到综合题子题数组中
				JSON.parse($scope.questions_Json.answerAnalysis).forEach( function(element, index) {
                    if(typeof element.questions_Json=="string"){
					    element.questions_Json=JSON.parse(element.questions_Json);
                    }
//					console.log(element.questions_Json.answer+"".replace(/(^\s+)|(\s+$)/g, ""));

$scope.comprehensiveChildList.push({
  OptionList:[],
  type:element.questions_Type,
  answer:answertrim(element.questions_Json.answer),
  id:guid.newGUID(),
  title:element.questions_Json.title.replace("[单选]","").replace("[多选]","").replace("[判断]","").replace("[问答]",""),
  answerAnalysis:element.questions_Json.answerAnalysis,
  score:element.score
});
						//解析 并循环 综合题子题选项 然后将对象插入到综合题子题数组中的子题选项数组中
						if (element.questions_Json.options!=undefined) {//单选 //多选
							element.questions_Json.options.forEach( function(chile, chileindex) {
								$scope.comprehensiveChildList[index].OptionList.push({option:$scope.optionChar[chileindex],
									optionvalue:chile,
									sort:chileindex,
									check:false});
						if (element.questions_Type=="1") //单选
						{
							if (element.questions_Json.answer==$scope.optionChar[chileindex]) {
								$scope.comprehensiveChildList[index].OptionList[chileindex].check=true;
							}
						}else if(element.questions_Type=="2"){//多选
							if (element.questions_Json.answer.indexOf($scope.optionChar[chileindex])!=-1) {
								$scope.comprehensiveChildList[index].OptionList[chileindex].check=true;
							}
						}
					});
						}


						

					});
				break;
			}
		}

		//清空对象信息
		$scope.clearQuesText=function(){
			$scope.questions_Json={
				answer:"",
				answerAnalysis:"",
				options:[],
				title:"",
				score:0
			};
			$scope.comprehensiveChildList=[];
			$scope.OptionList=[];
			$scope.BxingQuestionList=[];
		}
		/***********************************************************复选框*****************************************************/
  $scope.selectList=[];//选中之后的对象容器

  $scope.selectAll = function() {
  	$scope.select_all=!$scope.select_all;
  	if ($scope.select_all) {
  		$scope.selectList=angular.copy($scope.List);
  	}else{
  		$scope.selectList=[];
  	}
  };

  $scope.setCheck=function(obj,event){
  	
  	event = window.event || event;
  	event.stopPropagation();
  	var index=$scope.containsList($scope.selectList,obj);
//  	console.log(obj);
if (index>=0) 
{
  $scope.selectList.splice(index,1);
}else {
  $scope.selectList.push(obj);
}

if ($scope.selectList.length==$scope.List.length) {
  $scope.select_all=true;
}else{
  $scope.select_all=false;
}
}

$scope.containsList = function (arr, obj) {

 try {
  var i = arr.length;
  while (i--) {
   if (arr[i].questions_Id === obj.questions_Id) {
    return i;
  }
}
return -1;
} catch (e) {
            // statements
            return -1;
          }
        }
        /***************************************删除************************************************************/
        $scope.Del=function(obj,index){
             if(!$scope.btnlist.delinfo){
                Msg.warning("无权限操作！");
                return;
            }
          if(index==0||index=="0"||index==undefined||index==""||index==null){
            $scope.delitem=obj;
            index=0;
          }else{
            obj=$scope.delitem;
          }
          if(obj!=undefined&&obj!=""){$scope.selectList=[obj];}

          $scope.delpaperId={questions_Id:[],userid: sysUserInfo.getuserinfo().user_ID,orgid: sysUserInfo.getuserinfo().organization_ID,paper_id:$scope.params.paper_id}; 
          if ($scope.selectList.length<=0) {
            $scope.isloading=false;
            return Msg.warning("请选择要删除的数据!");
          }
          MsgCon.delnoicon().then(function (flag) {
            if (flag) {
              $scope.isloading=true;
              $scope.selectList.forEach(function(element, index) {
                $scope.delpaperId.questions_Id.push(element.questions_Id);
                $scope.List.splice($scope.containsList($scope.List,element),1);
              });
              $scope.selectList=[];
              RTS.questionDel($scope.delpaperId).then(function(data){
                $scope.delpaperId.questions_Id=[];
                $scope.isloading=false;
                if (data.errorcode == "0") {
                 Msg.success("删除成功");
                 $scope.TipShow();
                 if ($scope.List.length<=0) {
                  $scope.GetList();
                  $scope.select_all=false;
                }
              }else{
               Msg.error("请求数据有误");
             }
           });
            }else{
              $scope.isloading=true;
            }
          });
        }



//显示提示
$scope.showrepetitionRate=false;
$scope.showexamCount=false;
$scope.showMsg=function(val){
	switch (val) {
		case 1:
		$scope.showrepetitionRate=true;
		break;
		case 2:
		$scope.showexamCount=true;
		break;

	}
}
    //隐藏提示
    $scope.hideMsg=function(val){
    	switch (val) {
    		case 1:
    		$scope.showrepetitionRate=false;
    		break;
    		case 2:
    		$scope.showexamCount=false;
    		break;
    		
    	}
    }
//判定考试分数显示隐藏
$scope.totalScoreShow=function(){
//判定试卷类型
if ($scope.paperObj.paper_Random==1) {
		//固定卷
		if ($scope.paperObj.paper_id=="") {
			return false;
		}else {
			return true;
		}
	}
	else {
		$scope.paperObj.totalScore=0;
		$scope.paperObj.Rule.forEach(function(element) {
			$scope.paperObj.totalScore+=element.Score_per_question*element.Number_of_questions;
		});
		
		return true;
	}
}

$scope.TipShow=function(){
	try {
   if ($scope.params.paper_id!=undefined&&$scope.params.paper_id.length>0) {
    Msg.success("题目操作成功。全部题目操作完成后。请点击右上角 试卷题目保存进行刷新试卷");
  }else{
    Msg.success("题目操作成功。");
  }
} catch(e) {

  console.log(e);
}


}

/*******************************************************************题库弹窗*****************************************/


$scope.modalStyle={"width":document.body.offsetWidth+"px","height":document.body.offsetHeight+"px"};
$scope.OpenQueHtml=function(paperid){	
  var url="";
  var url2="";
  if ($rootScope.requestUrl.indexOf("http") == -1) {
    url=window.location.protocol;
  }
  if ($rootScope.DeployUrl.indexOf("http") == -1) {
    url2=window.location.protocol;
  }
	var endcodeurl=url+$rootScope.requestUrl+'/questionLook/QuestionBydoc?isCreateHtml=1&paper_id='+paperid+'&id='+sysUserInfo.getuserinfo().user_ID+'&url='+url2+$rootScope.DeployUrl+'/system/views/examination/examend.html';
	$scope.someUrl = $sce.trustAs($sce.RESOURCE_URL,$rootScope.questionUrl+endcodeurl);
	$scope.iframeShow=true;
}
$scope.closeuser=function(){
	$scope.iframeShow=false;
	$scope.someUrl="";
	
}
  //页面监听iframe关闭
  $scope.$watch('iframeShow', function (newValue, oldValue, scope) {
  	if (!$scope.iframeShow && $scope.iframeShow != undefined) {
  		var examresult="";
  		try{
        examresult=JSON.parse(document.getElementById('itemobj').value).message;
      }
      catch(e){
       console.log(e);
     }
     if (examresult!="") {
  			$scope.params.knowledge_Id="";
  			$scope.GetList();
  		}

  	} 
  }, true);

}]);



